package com.gitee.dolt.redisson.lock;

import com.gitee.dolt.core.lock.DistributedLock;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * redis分布式锁实现
 *
 * @author LYH
 */
@Slf4j
@RequiredArgsConstructor
public class RedissonDistributedLock implements DistributedLock {

    private final RedissonClient redissonClient;

    @Override
    public boolean lock(String key, long expire, int retryTimes, long sleepMillis) {
        RLock lock = redissonClient.getLock(key);
        try {
            boolean result = lock.tryLock(expire, TimeUnit.MILLISECONDS);
            while ((!result) && retryTimes-- > 0) {
                try {
                    log.debug("get redisDistributeLock failed, retrying..." + retryTimes);
                    Thread.sleep(sleepMillis);
                } catch (InterruptedException e) {
                    log.warn("Interrupted!", e);
                    Thread.currentThread().interrupt();
                }
                result = lock.tryLock(expire, TimeUnit.MILLISECONDS);
            }
            return result;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;

    }

    @Override
    public boolean releaseLock(String key) {
        RLock lock = redissonClient.getLock(key);
        lock.unlock();
        return true;
    }

    @Override
    public boolean isLocked(String key) {
        RLock lock = redissonClient.getLock(key);
        return lock.isLocked();
    }
}
